package com.git.intercepor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.git.annotation.CSRFRefresh;
import com.git.annotation.CSRFVerify;
import com.git.utils.CSRFTokenUtil;

/*
 * 这里现在设置为通过
 */
public class CSRFInteceptor implements HandlerInterceptor {
	public static final Logger logger = Logger.getLogger(CSRFInteceptor.class);
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//如果访问的不是方法，就直接通过
		if (! (handler instanceof HandlerMethod)) {
			return true;
		}
		//得到访问的方法
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();
		
		//判断是否有@VerifyCSRFAnnotation注解
		CSRFVerify annotation = method.getAnnotation(CSRFVerify.class);
		if (annotation==null) {
			//没有注解，直接通过
			return true;
		}
		//验证通过直接通过
		if (CSRFTokenUtil.valiToken(request)) {
			return true;
		}
		throw new RuntimeException("token无效");
	}

	/**
	 * 响应返回的时候，保证session中肯定有token
	 * 如果方法上有刷新token，这里就刷新token，用来防止重复提交代码
	 * @param request
	 * @param response
	 * @param handler
	 * @param modelAndView
	 * @throws Exception
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		//这里用来保证session中有token
		CSRFTokenUtil.setToken(request);
		
		//得到访问的方法
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();
		
		//判断是否有@VerifyCSRFAnnotation注解
		CSRFRefresh annotation = method.getAnnotation(CSRFRefresh.class);
		if (annotation!=null) {
			CSRFTokenUtil.refreshToken(request);
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
